package main

import (
	"fmt"
	"golang.org/x/net/websocket"
	"net/http"
)



func WebSocketStart(addr string) {

	http.Handle("/", websocket.Handler(Echo))

	if err := http.ListenAndServe(addr, nil); err != nil {

		fmt.Println(err)
	}
}

func Echo(conn *websocket.Conn) {
	ipStr := conn.RemoteAddr().String()
	fmt.Printf("Echo ip=%s\n" ,ipStr)

	defer func() {

		fmt.Printf("DialTCP  err recover()") //有效
		fmt.Println(recover()) //有效
		conn.Close()
	}()

	for {
		var wsbuf [1024]byte
		tcpbufLen, err := conn.Read(wsbuf[:])

		if err != nil {
			fmt.Printf("Echo err,ip=%s err: %v\n",ipStr, err)
			break
		}
		conn.Write(wsbuf[:tcpbufLen])
		fmt.Printf("Echo read,ip=%s,data: %v\n", ipStr, wsbuf[:tcpbufLen])
	}
}



func main() {


	soketAddr:=":9910"

	go WebSocketStart(soketAddr)

	select {}
}